package com.dragon.english_practice_back.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragon.english_practice_back.entity.Session;
import com.dragon.english_practice_back.reponse.Result;
import com.dragon.english_practice_back.service.AuthenticationUtil;
import com.dragon.english_practice_back.service.MessageService;
import com.dragon.english_practice_back.service.SessionService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/session")
@Slf4j
@AllArgsConstructor
public class SessionController {
    AuthenticationUtil authenticationUtil;
    SessionService sessionService;
    MessageService messageService;

    @GetMapping("/getAll")
    public Result<List<Session>> getSessions(){
        Result<List<Session>> result = new Result<>(200, "all session",
                sessionService.list(new QueryWrapper<Session>().select("id", "create_date", "name").eq("creator_id", authenticationUtil.id()).orderByDesc("create_date"))
        );

        return result;
    }

    @PostMapping("/create")
    @Transactional
    public Result<Session> createSession(){
        Session session = new Session();
        session.setCreatorId(authenticationUtil.id());
        session.setName("新会话");
        // 获取当前系统时间，精确到6位微秒
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
        String formattedDateTime = now.format(formatter);

        // 将格式化的时间字符串转换为Date对象
        Date currentDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
            currentDate = sdf.parse(formattedDateTime);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.no("无法获取系统时间");
        }
        session.setCreateDate(currentDate);
        Session savedSession = null;
        if (sessionService.save(session)){
            savedSession = sessionService.getOne(new QueryWrapper<Session>().select("id", "create_date", "name").eq("create_date", currentDate));
        }
        //如果saveSession不是空则返插入一条初始问候消息在会话中，并返回给前端
        if(ObjectUtil.isNotNull(savedSession)){
            messageService.insertAssistantMessage(authenticationUtil.id(), "Hello, I'm the English chatting practice partner. Chat with me quickly! \uD83C\uDF1E", savedSession.getId());

            return new Result<Session>(200, "new session", savedSession);
        }
        return Result.no("不能创建session");
    }

    //删除会话
    @DeleteMapping("/delete/{sessionId}")
    public Result<Void> deleteSession(@PathVariable Long sessionId) {
        // 检查会话是否存在
        Session session = sessionService.getById(sessionId);
        if (session == null) {
            return new Result<>(404, "会话不存在", null);
        }

        // 检查当前用户是否有权限删除这个会话
        if (!session.getCreatorId().equals(authenticationUtil.id())) {
            return new Result<>(403, "没有权限删除此会话", null);
        }

        // 删除会话
        boolean success = sessionService.removeById(sessionId);
        if (success) {
            return new Result<>(200, "会话删除成功", null);
        } else {
            return new Result<>(500, "会话删除失败", null);
        }
    }

    @PutMapping("/rename/{sessionId}")
    public Result<Session> renameSession(@PathVariable Long sessionId, @RequestParam String newName) {
        log.info("Renaming session {} to {} for user {}", sessionId, newName, authenticationUtil.id());

        try {
            // 检查会话是否存在
            Session session = sessionService.getById(sessionId);
            if (session == null) {
                log.warn("Session {} not found", sessionId);
                return new Result<>(404, "会话不存在", null);
            }

            // 检查用户是否有权限修改这个会话
            if (!session.getCreatorId().equals(authenticationUtil.id())) {
                log.warn("User {} does not have permission to rename session {}", authenticationUtil.id(), sessionId);
                return new Result<>(403, "没有权限修改此会话", null);
            }

            // 更新会话名称
            session.setName(newName);
            boolean updated = sessionService.updateById(session);

            if (updated) {
                log.info("Session {} renamed successfully", sessionId);
                return new Result<>(200, "会话名称修改成功", session);
            } else {
                log.error("Failed to rename session {}", sessionId);
                return new Result<>(500, "会话名称修改失败", null);
            }
        } catch (Exception e) {
            log.error("Error occurred while renaming session {}: {}", sessionId, e.getMessage(), e);
            return new Result<>(500, "修改会话名称过程中发生错误", null);
        }
    }
}
